//
//  L0PlugSuitTableItem.m
//  PlugSuit
//
//  Created by ∞ on 21/10/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "L0PlugSuitTableItem.h"
#import "L0PlugSuitRegistry.h"

@implementation L0PlugSuitTableItem

- (id) initWithBundle:(NSBundle*) bundle pane:(L0PlugSuitPreferencePane*) pane {
	if (self = [super init]) {
		_bundle = [bundle retain];
		_pane = pane;
		[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(_prefsChanged:) name:@"L0PlugSuitPreferencesChanged" object:@"net.infinite-labs.PlugSuit"];
	}
	
	return self;
}

- (void) dealloc {
	[_bundle release];
	[_icon release];
	[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
	[super dealloc];
}

- (NSString*) path {
	return [_bundle bundlePath];
}

- (NSString*) name {
	return [[L0PlugSuitRegistry sharedInstance] userVisibleNameOfBundle:_bundle];
}

- (NSString*) version {
	NSString* version = [[[_bundle infoDictionary] objectForKey:@"CFBundleShortVersionString"] description];
	if (!version)
		version = [[[_bundle infoDictionary] objectForKey:@"CFBundleVersion"] description];
	return version;
}

- (NSString*) longName {
	NSString* version = [self version];
	if (version)
		return [self name];
	else
		return [NSString stringWithFormat:@"%@ (%@)", [self name], version];
}

- (NSImage*) icon {
	if (_icon)
		return _icon;
	
	NSString* iconPath;
	if (iconPath = [[_bundle infoDictionary] objectForKey:@"CFBundleIcon"]) {
		NSString* type = ([iconPath rangeOfString:@"."].location != NSNotFound)? @"" : @"icns";
		iconPath = [_bundle pathForResource:iconPath ofType:type];
		
		if ([[NSFileManager defaultManager] fileExistsAtPath:iconPath])
			_icon = [[NSImage alloc] initWithContentsOfFile:iconPath];
	}
	
	if (!_icon)
		_icon = [[[NSWorkspace sharedWorkspace] iconForFile:[self path]] retain];
	[_icon setSize:NSMakeSize(32, 32)];
	
	return _icon;
}

- (BOOL) enabled {
	return [L0PlugSuitRegistry isEnabled:_bundle];
}

- (void) setEnabled:(BOOL) enabled {
	if (enabled)
		[L0PlugSuitRegistry enable:_bundle];
	else
		[L0PlugSuitRegistry disable:_bundle shouldAutoEnableOnVersionChange:NO];
	
	[_pane warnAboutApplicationRestart:enabled];
}

- (void) _prefsChanged:(NSNotification*) notif {
	[self willChangeValueForKey:@"enabled"];
	[L0PlugSuitRegistry clearDisabledPlugInsCache];
	[self didChangeValueForKey:@"enabled"];
}

- (L0PlugSuitPreferencePane*) pane { return _pane; }

@end
